<template>
  <div class="home-container">
    <!-- 统计卡片 -->
    <n-grid cols="1 s:2 m:4" :x-gap="16" :y-gap="16">
      <n-gi>
        <n-card class="stat-card">
          <div class="stat-content">
            <n-icon size="36" :color="iconColors.user">
              <PeopleOutline />
            </n-icon>
            <div class="stat-info">
              <div class="stat-title">用户总数</div>
              <div class="stat-value">{{ stats.users }}</div>
            </div>
          </div>
        </n-card>
      </n-gi>
      <n-gi>
        <n-card class="stat-card">
          <div class="stat-content">
            <n-icon size="36" :color="iconColors.equipment">
              <ServerOutline />
            </n-icon>
            <div class="stat-info">
              <div class="stat-title">设备总数</div>
              <div class="stat-value">{{ stats.equipments }}</div>
            </div>
          </div>
        </n-card>
      </n-gi>
      <n-gi>
        <n-card class="stat-card">
          <div class="stat-content">
            <n-icon size="36" :color="iconColors.command">
              <CodeWorkingOutline />
            </n-icon>
            <div class="stat-info">
              <div class="stat-title">命令总数</div>
              <div class="stat-value">{{ stats.commands }}</div>
            </div>
          </div>
        </n-card>
      </n-gi>
      <n-gi>
        <n-card class="stat-card">
          <div class="stat-content">
            <n-icon size="36" :color="iconColors.company">
              <BusinessOutline />
            </n-icon>
            <div class="stat-info">
              <div class="stat-title">公司总数</div>
              <div class="stat-value">{{ stats.companies }}</div>
            </div>
          </div>
        </n-card>
      </n-gi>
    </n-grid>

    <!-- 系统信息和活动列表 -->
    <n-grid cols="1 m:2" :x-gap="16" :y-gap="16" style="margin-top: 16px">
      <n-gi>
        <n-card title="系统信息">
          <div class="info-item">
            <span class="info-label">系统名称:</span> {{ systemInfo.name }}
          </div>
          <div class="info-item">
            <span class="info-label">版本号:</span> {{ systemInfo.version }}
          </div>
          <div class="info-item">
            <span class="info-label">部署时间:</span> {{ systemInfo.deploymentTime ? formatDate(systemInfo.deploymentTime) : formatDate(new Date()) }}
          </div>
          <div class="info-item">
            <span class="info-label">更新时间:</span> {{ systemInfo.updateTime ? formatDate(systemInfo.updateTime) : formatDate(new Date()) }}
          </div>
          <div class="info-item">
            <span class="info-label">系统状态:</span> {{ systemInfo.status }}
          </div>
        </n-card>
      </n-gi>
      <n-gi>
        <n-card title="最近活动">
          <n-list>
            <n-list-item v-for="(activity, index) in recentActivities" :key="index">
              <n-thing :title="activity.title" :description="activity.time">
                {{ activity.content }}
              </n-thing>
            </n-list-item>
          </n-list>
        </n-card>
      </n-gi>
    </n-grid>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { NCard, NGrid, NGi, NSpace, NIcon, NList, NListItem, NThing } from 'naive-ui';
import { PeopleOutline, ServerOutline, CodeWorkingOutline, BusinessOutline } from '@vicons/ionicons5';
import { useSettingsStore } from '../stores/settings';
import { getDashboardStats, getRecentActivities, getSystemInfo } from '@/api/dashboard';

const settingsStore = useSettingsStore();

// 动态设置的图标颜色
const iconColors = computed(() => {
  const isDark = settingsStore.isDarkTheme;
  return {
    user: isDark ? '#4098fc' : '#2080f0',
    equipment: isDark ? '#36ad6a' : '#18a058',
    command: isDark ? '#fcb040' : '#f0a020',
    company: isDark ? '#e84c60' : '#d03050'
  };
});

// 统计数据
const stats = reactive({
  users: 0,
  equipments: 0,
  commands: 0,
  companies: 0
});

// 系统信息
const systemInfo = reactive({
  name: '后台管理系统',
  version: 'v1.0.0',
  deploymentTime: '',
  updateTime: '',
  status: '正常运行'
});

// 活动数据
const recentActivities = ref([]);

// 加载统计数据
const loadStatsData = async () => {
  console.log('正在加载统计数据...');
  try {
    const res = await getDashboardStats();
    console.log('统计数据加载完成:', res);
    if (res && res.data && res.code === 200) {
      stats.users = res.data.users;
      stats.equipments = res.data.equipments;
      stats.commands = res.data.commands;
      stats.companies = res.data.companies;
      console.log('统计数据已更新:', stats);
    } else {
      console.error('统计数据响应格式不正确:', res);
    }
  } catch (error) {
    console.error('获取统计数据失败：', error);
  }
};

// 加载活动数据
const loadActivitiesData = async () => {
  console.log('正在加载活动数据...');
  try {
    const res = await getRecentActivities();
    console.log('活动数据加载完成:', res);
    if (res && res.data && res.code === 200) {
      recentActivities.value = res.data;
      console.log('活动数据已更新:', recentActivities.value);
    } else {
      console.error('活动数据响应格式不正确:', res);
    }
  } catch (error) {
    console.error('获取活动数据失败：', error);
  }
};

// 加载系统信息
const loadSystemInfoData = async () => {
  console.log('正在加载系统信息...');
  try {
    const res = await getSystemInfo();
    console.log('系统信息加载完成:', res);
    if (res && res.data && res.code === 200) {
      systemInfo.name = res.data.name || systemInfo.name;
      systemInfo.version = res.data.version || systemInfo.version;
      systemInfo.deploymentTime = res.data.deployTime || res.data.deploymentTime || '';
      systemInfo.updateTime = res.data.updateTime || res.data.updateTime || '';
      systemInfo.status = res.data.serverStatus || res.data.status || '正常运行';
      console.log('系统信息已更新:', systemInfo);
    } else {
      console.error('系统信息响应格式不正确:', res);
    }
  } catch (error) {
    console.error('获取系统信息失败：', error);
  }
};

// 格式化日期
const formatDate = (date) => {
  if (typeof date === 'string') {
    date = new Date(date);
  }
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

onMounted(async () => {
  console.log('HomeView组件已挂载，开始加载数据...');
  // 加载所有数据
  try {
    await loadStatsData();
    await loadActivitiesData();
    await loadSystemInfoData();
    console.log('所有数据已加载完成');
  } catch (error) {
    console.error('数据加载过程出错:', error);
  }
});
</script>

<style scoped>
.home-container {
  padding: 4px;
}

.stat-card {
  height: 110px;
  border-radius: 4px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-info {
  margin-left: 16px;
}

.stat-title {
  font-size: 14px;
  opacity: 0.7;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  margin-top: 5px;
}

.info-item {
  line-height: 2;
}

.info-label {
  display: inline-block;
  width: 80px;
  opacity: 0.7;
}

@media (max-width: 768px) {
  .stat-card {
    height: 90px;
  }
  
  .stat-value {
    font-size: 20px;
  }
}
</style>
